<style>
.groupCompany {
  padding: 10px;
  min-height: 600px;
}
.smoke-top-title {
  margin-bottom: 10px;
  margin-left: 4px;
}
.smoke-count-item {
  border: 1px solid #666;
  border-radius: 5px;
  max-width: 200px;
  padding: 15px 0 10px;
  margin-right: 1.5vw;
  text-align: center;
  cursor: pointer;
}
.smoke-count-item > .smoke-p-title {
  font-size: 22px;
  line-height: 1;
}
.smoke-count-item > .smoke-p-desc {
  margin-top: 10px;
  font-size: 12px;
  color: #666;
}
.color-red {
  color: #e44e1d;
  border-color: #e44e1d;
}
.color-gold {
  color: #dbd148;
  border-color: #dbd148;
}
.color-orange {
  color: #eba035;
  border-color: #eba035;
}
.color-blue {
  color: #3089ff;
  border-color: #3089ff;
}
.color-green {
  color: #19be6b;
  border-color: #19be6b;
}
.color-gray {
  color: #808695;
  border-color: #c5c8ce;
}
.color-cyan {
  color: #13c2c2;
  border-color: #13c2c2;
}
</style>

<template>
  <div class="groupCompany">
    <div style="background-color:#fff;padding:10px 10px 0;border-radius:4px;position:relative;">
      <Form ref="searchForm"
            :model="searchForm"
            value="true"
            inline>
        <Row>
          <Form-item>
            <Cascader :data="deptCascader"
                      v-model="searchForm.deptCascader"
                      :filterable="true"
                      placeholder="请选择所属部门"
                      transfer></Cascader>
          </Form-item>
          <Form-item>
            <Select v-model="searchForm.alarmType"
                    placeholder="请选择"
                    style="width:120px;">
              <Option v-for="item in alarmTypeCombo"
                      :value="item.key"
                      :key="item.value">{{ item.value }}</Option>
            </Select>
          </Form-item>
          <Form-item>
            <Select v-model="searchForm.alarmStat"
                    placeholder="请选择"
                    style="width:120px;">
              <Option v-for="item in alarmStatCombo"
                      :value="item.key"
                      :key="item.value">{{ item.value }}</Option>
            </Select>
          </Form-item>
          <Form-item>
            <Input placeholder="设备IMEI号"
                   v-model="searchForm.imei"
                   maxlength="50"></Input>
          </Form-item>
          <Form-item>
            <Input placeholder="店铺名称"
                   v-model="searchForm.shopName"
                   maxlength="50"></Input>
          </Form-item>
          <Form-item>
            <DatePicker type="date"
                        placeholder="开始日期"
                        style="width: 200px"
                        v-model="searchForm.startTime"></DatePicker>
          </Form-item>
          <Form-item>
            <DatePicker type="date"
                        placeholder="结束时间"
                        style="width: 200px"
                        v-model="searchForm.endTime"></DatePicker>
          </Form-item>
          <Button type="primary"
                  icon="ios-search"
                  @click="doSearchTableList">搜 索</Button>
          <Button type="warning"
                  icon="ios-color-wand"
                  @click="resetSearch">重置</Button>
          <!-- <Button
            @click="toExcel"
            type="error"
            icon="md-cloud-download"
            v-perms="'bss:alarm:export'"
          >导出</Button>-->
        </Row>
      </Form>
    </div>
    <!--table-->
    <Row>
      <Table stripe
             size="small"
             :columns="tableColums"
             :data="tableData"
             :loading="tableLoading"></Table>
    </Row>
    <Row>
      <Page :total="total"
            :page-size="currentPageSize"
            :current="currentPage"
            @on-change="changeCurrentPage"
            @on-page-size-change="changePageSize"
            show-total
            show-sizer
            style="float:right;margin-top:10px"></Page>
    </Row>
    <!--管理-->
    <maintListForm :modalShow="formShow"
                   :modalFormTitle="formTitle"
                   :parentForm="parentForm"
                   @listenModalForm="hideModel"
                   @refreshTableList="getTableList"></maintListForm>
    <!--是否删除框-->
    <Modal v-model="delModal"
           width="360">
      <p slot="header"
         style="color:#f60;text-align:center">
        <Icon type="information-circled"></Icon>
        <span>删除确认</span>
      </p>
      <div style="text-align:center">
        <p>是否继续删除？</p>
      </div>
      <div slot="footer">
        <Button type="error"
                size="large"
                long
                :loading="btnLoading"
                @click="comfirmDel">删除</Button>
      </div>
    </Modal>
    <audio id="audioPlay2"
           src="static/119.ogg"
           controls="controls"
           style="display:none;"></audio>
  </div>
</template>

<script>
import { getAlarmPagedList, alarmCount, getAlarmListExcel } from '@/api/monitor'
import { getDeptCascader } from '@/api/system'
import { formatDate } from '@/libs/util'
import maintListForm from './maintListForm.vue'
import expandRow from './table-expand.vue'
import config from '@/config'
const baseUrl =
  process.env.NODE_ENV === 'development'
    ? config.baseUrl.dev
    : config.baseUrl.pro
export default {
  components: {
    maintListForm,
    expandRow
  },
  data() {
    return {
      tableColums: [
        {
          type: 'expand',
          width: 50,
          render: (h, params) => {
            return h(expandRow, {
              props: {
                row: params.row
              }
            })
          }
        },
        {
          align: 'center',
          title: '设备名称',
          key: 'devName'
        },
        {
          align: 'center',
          title: '安装位置',
          key: 'installAddr'
        },
        {
          align: 'center',
          title: '店铺名称',
          key: 'shopName'
        },
        {
          align: 'center',
          title: '告警类型',
          key: 'alarmType',
          render: (h, params) => {
            let alarmTypeTxt = this.alarmTypeCombo.find(
              a => a.key == params.row.alarmType
            ).value
            let alarmTypeColor = this.alarmTypeColorList.find(
              a => a.key == params.row.alarmType
            ).value
            return h(
              'span',
              {
                style: {
                  color: alarmTypeColor
                }
              },
              alarmTypeTxt
            )
          }
        },
        {
          align: 'center',
          title: '告警内容',
          key: 'alarmDetail'
        },
        {
          align: 'center',
          title: '告警时间',
          key: 'alarmTime'
        },

        {
          align: 'center',
          title: '告警状态',
          key: 'alarmStat',
          render: (h, params) => {
            let alarmStatTxt = this.alarmStatCombo.find(
              a => a.key == params.row.alarmStat
            ).value
            let alarmStatColor = this.alarmStatColorList.find(
              a => a.key == params.row.alarmStat
            ).value
            return h(
              'span',
              {
                style: {
                  color: alarmStatColor
                }
              },
              alarmStatTxt
            )
          }
        },
        {
          align: 'center',
          title: '处理人',
          key: 'dealBy'
        },
        {
          align: 'center',
          title: '处理时间',
          key: 'dealTime'
        },
        {
          title: '操作',
          align: 'center',
          render: (h, params) => {
            let actions = []

            actions.push(
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.manageItem(params.row)
                    }
                  }
                },
                '管理'
              )
            )
            return h('div', actions)
          }
        }
      ],
      tableData: [],
      tableLoading: false,
      total: 0,
      currentPage: 1,
      currentPageSize: 20,
      formShow: false,
      formTitle: '添加联网单位',
      parentForm: {},
      delModal: false,
      delId: '', //删除的Id
      btnLoading: false,
      searchForm: {
        deptId: 0,
        alarmType: 0,
        alarmStat: 0,
        imei: '',
        shopName: '',
        startTime: '',
        endTime: '',
        size: 10,
        current: 1,
        deptCascader: []
      },
      deptCascader: [],
      alarmTypeCombo: [
        { key: 0, value: '告警类型' },
        { key: 1, value: '离线' },
        // { key: 2, value: "火警" },
        { key: 3, value: '传感器故障' },
        { key: 4, value: '拆除告警' },
        { key: 5, value: '低压告警' },
        { key: 6, value: '火警解除' },
        { key: 99, value: '未知' }
      ],
      alarmTypeColorList: [
        { key: 0, value: '#495060' },
        { key: 1, value: '#f16700' },
        { key: 2, value: '#e4393c' },
        { key: 3, value: '#00b711' },
        { key: 4, value: '#d3adf7' },
        { key: 5, value: '#495060' }
      ],
      alarmStatCombo: [
        { key: 0, value: '确认状态' },
        { key: 1, value: '未确认' },
        { key: 2, value: '已确认' }
      ],
      alarmStatColorList: [
        { key: 1, value: '#f54d50' },
        { key: 2, value: '#5cb85c' }
      ],
      alarmStc: {
        errorAlarm: 0,
        fireAlarmHis: 1,
        preAlarm: 0,
        preAlarmHis: 0,
        errorAlarmHis: 1,
        fireAlarm: 1
      },
      devStc: { bindDev: 0, onlineDev: 1, unbindDev: 2, offlineDev: 0 },
      shopStc: { total: 4 },
      malfunctionCount: 0,
      gcCount: 0,
      mysocket: null
    }
  },
  created() {},
  mounted() {
    this.getDeptCascader()
    // this.getAlramCount();
    this.getTableList()
    // this.socketConn();
  },
  methods: {
    async getAlramCount() {
      let res = await alarmCount({})
      if (res.code == 0) {
        if (res.data.alarmStc) {
          this.alarmStc = res.data.alarmStc
        }
        if (res.data.devStc) {
          this.devStc = res.data.devStc
        }
        if (res.data.shopStc) {
          this.shopStc = res.data.shopStc
        }
      }
    },
    async getDeptCascader() {
      let res = await getDeptCascader()
      if (res.code == 0) {
        this.deptCascader = res.data
      }
    },
    resetSearch() {
      this.searchForm.alarmType = 0
      this.searchForm.alarmStat = 0
      this.searchForm.imei = ''
      this.searchForm.shopName = ''
      this.searchForm.start = ''
      this.searchForm.end = ''
      this.searchForm.deptCascader = []
    },
    doSearchTableList() {
      this.currentPage = 1
      this.getTableList()
    },
    async getTableList() {
      this.tableLoading = true
      this.searchForm.current = this.currentPage
      this.searchForm.size = this.currentPageSize
      if (this.searchForm.deptCascader.length < 1) {
        this.searchForm.deptId = 0
      } else {
        var arr = this.searchForm.deptCascader
        this.searchForm.deptId = arr[arr.length - 1]
      }
      let params = {
        alarmType: this.searchForm.alarmType,
        alarmStat: this.searchForm.alarmStat,
        deptId: this.searchForm.deptId,
        imei: this.searchForm.imei,
        shopName: this.searchForm.shopName,
        start: '',
        end: '',
        size: this.searchForm.size,
        current: this.searchForm.current,
        isMaintPage: true
      }

      let startDate = this.searchForm.startTime
      let endDate = this.searchForm.endTime
      if (startDate instanceof Date) {
        params.start = formatDate(startDate)
      }
      if (endDate instanceof Date) {
        params.end = formatDate(endDate)
      }
      const result = await getAlarmPagedList(params)

      if (result.code == 0) {
        let res = result.data
        this.total = res.total
        this.tableData = res.records
      }
      this.tableLoading = false
    },
    changeCurrentPage(num) {
      this.currentPage = num
      this.getTableList()
    },
    changePageSize(pageSize) {
      this.currentPageSize = pageSize
      this.getTableList()
    },
    delItem(Id) {
      this.delId = Id
      this.delModal = true
    },
    async comfirmDel() {
      this.btnLoading = true
      try {
        const res = await delGroupCompany(this.delId)
        if (res.code == 0) {
          this.getTableList()
          this.delModal = false
        }
      } catch (err) {
        console.log(err)
        this.$Message.error('服务器异常，稍后再试')
      }
      this.btnLoading = false
    },
    hideModel() {
      this.formShow = false
    },
    manageItem(row) {
      this.parentForm = JSON.parse(JSON.stringify(row))
      this.formTitle = '告警处理'
      this.formShow = true
    },
    routTo(status) {
      //页面跳转
      this.$router.push({
        name: 'device',
        query: {
          status: status
        }
      })
    },
    socketConn() {
      let socketUrl = baseUrl.split('/')[2]
      let loginName = sessionStorage.getItem('loginName')
      //if (this.mysocket!=null&&this.mysocket.readyState === this.mysocket.OPEN) {
      //        return;
      //} 无效果，切换页面后无法保持连接
      this.mysocket = new WebSocket(
        `ws://${socketUrl}/smokev2/websocket/${loginName}`
      )
      //打开事件
      this.mysocket.onopen = () => {
        console.log('Socket 已打开')
      }
      //获得消息事件
      this.mysocket.onmessage = msg => {
        console.log(msg.data)
        var obj = JSON.parse(msg.data)
        console.log(obj.alarmData)

        // if (obj.msgType == "alarm") {
        this.$Notice.warning({
          title: obj.alarmData,
          desc: '设备：' + obj.deviceName + ',地址：' + obj.addr,
          duration: 0
        })
        if (obj.msgType == 'alarm' && obj.streamId == 'fireAlarm') {
          let audioPlay = document.getElementById('audioPlay2')

          audioPlay.play()
        }
        this.doSearchTableList()
        this.getAlramCount()
        // }
      }
      //关闭事件
      this.mysocket.onclose = () => {
        console.log('Socket已关闭')
      }
      //发生了错误事件
      this.mysocket.onerror = () => {
        console.log('Socket发生了错误')
      }
      this.$router.afterEach(() => {
        this.mysocket.close()
      })
    },
    async toExcel() {
      this.tableLoading = true
      let params = {
        alarmType: this.searchForm.alarmType,
        alarmStat: this.searchForm.alarmStat,
        deptId: this.searchForm.deptId,
        imei: this.searchForm.imei,
        shopName: this.searchForm.shopName,
        start: '',
        end: ''
      }

      let startDate = this.searchForm.startTime
      let endDate = this.searchForm.endTime
      if (startDate instanceof Date) {
        params.start = formatDate(startDate)
      }
      if (endDate instanceof Date) {
        params.end = formatDate(endDate)
      }
      const res = await getAlarmListExcel(params)
      this.tableLoading = false
      if (res.code == 0) {
        const url = baseUrl + res.data
        window.open(url)
      } else {
        this.$Message.error(res.msg)
      }
    }
  }
}
</script>
